<template>
  <n-config-provider>
    <n-grid :x-gap="10" :y-gap="5" :cols="4">
      <n-grid-item>
        <n-button type="success" size="medium" @click="handleAdd">
          新增角色
        </n-button>
      </n-grid-item>
    </n-grid>
    
    <n-data-table
      :columns="columns"
      :data="roleList"
      :pagination="pagination"
      class="product-table"
    />
    <n-drawer v-model:show="drawerShow" :width="400" placement="right">
      <n-drawer-content :title="editData?'编辑角色':'新增角色'">
        <RoleForm :row-data="editData" @update-list="handleRefresh"/>
      </n-drawer-content>
    </n-drawer>
    
  </n-config-provider>
</template>

<script setup>
import { useMessage,NButton, NImage, NTag, useDialog } from 'naive-ui';
import { ref,h } from 'vue';
import { useRouter } from 'vue-router';
import RoleForm from './components/RoleForm.vue';
import { roleGetApi } from '../../api/user';
import { routes } from '../../router';
import { usePermission } from '../../hooks/permission';

// 操作按钮权限控制
const {canUse} = usePermission(['super'])

const roleList = ref([]);
roleGetApi().then(res=>{
  roleList.value = res.data.data
})


//表格配置
function createColumns({
  edit,
  del
}) {
  let columnArr = [
    {
      title: "角色ID",
      key: "_id"
    },
    {
      title: "角色名称",
      key: "roleName"
    },
    {
      title: "角色权限",
      key: "permission",
      render(row){
        let tagNodes = row.permission.map((key) => {
          return h(
            NTag,
            {type: 'success',size:'small'},
            {default: () => keyValues[key]}
          )
        })
        return tagNodes
      }
    },
    {
      title: "操作",
      key: "actions",
      render(row) { //自定义渲染表格内容的函数
        const btns = [
          {title:'编辑',type:'info',fuc:()=>{edit(row)}},
          {title:'删除',type:'error',fuc:()=>{del(row)}},
        ]
        const btnsNode = btns.map((item) => {
          return h(
            NButton,
            {type: item.type,size:'small',onClick:item.fuc},
            {default: () => item.title}
          )
        })
        return btnsNode
      }
    }
  ];
  if(!canUse){
    columnArr.pop()
  }
  return columnArr
}

const message = useMessage();
const dialog = useDialog()
const router = useRouter()
const columns=createColumns({
  edit(row) {
    drawerShow.value = true //显示抽屉
    editData.value = row
  },
  del(row){
    dialog.warning({
      title: '警告，删除后无法找回',
      content: `你确定要删除《${row.name}》商品吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        
      }
    })
    
  }
})
const pagination = ref(true)


//抽屉控制
const drawerShow = ref(false)
const handleAdd = ()=>{
  drawerShow.value = true
  editData.value = null
}


//渲染角色权限对应的菜单名称
function routesToKeyValue(routesArr){
    let obj = {}
    function loop(arr){ //递归函数
      arr.forEach(item=>{
        obj[item.path] = item.label //obj['/cart'] = '购物车管理'
        if(item.children){
          loop(item.children)
        }
      })
    }
    loop(routesArr)
    return obj
}
const keyValues = routesToKeyValue(routes[0].children)
console.log('路由数据键值对',keyValues);

// 复用新增与编辑逻辑
const editData = ref(null) //区分新增与编辑
//  接收子组件实时更新的数据
const handleRefresh = (formData)=>{
  console.log('接收到子组件数据',formData);
  drawerShow.value = false
  let len = roleList.value.length
  for(let i=0;i<len;i++){
    if(formData._id==roleList.value[i]._id){
      roleList.value[i] = formData //替换原数据
      return
    }
  }
  roleList.value.push(formData) //新增
}


</script>

<style lang="scss" scoped>
/* 深度选择器 */
.product-table :deep(.poster){
  height: 50px;
}
</style>